package com.lyc.service.impl;

import com.lyc.DTO.InternshipJobDTO;
import com.lyc.mapper.InternshipJobsMapper;
import com.lyc.mapper.PostMapper;
import com.lyc.pojo.InternshipJobs;
import com.lyc.pojo.Post;
import com.lyc.pojo.PostImages;
import com.lyc.service.InternshipJobsService;
import com.lyc.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class InternshipJobsServiceImpl implements InternshipJobsService {
    
    private static final Logger logger = LoggerFactory.getLogger(InternshipJobsServiceImpl.class);
    
    @Autowired
    private InternshipJobsMapper jobMapper;
    
    @Autowired
    private PostMapper postMapper;
    
    @Value("${upload.path}")
    private String uploadPath;
    
    /**
     * 添加实习/兼职信息
     * @param internshipJobDTO 实习/兼职信息DTO
     * @param coverFile 封面图片文件
     */
    @Transactional
    @Override
    public void addInternshipJob(InternshipJobDTO internshipJobDTO, MultipartFile coverFile) throws IOException {
        logger.info("开始添加实习/兼职信息");
        
        // 1. 验证必要字段
        validateInternshipJobDTO(internshipJobDTO);
        logger.info("数据验证通过");
        
        // 2. 创建帖子记录
        Post post = new Post();
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        post.setUserId(userId);
        post.setCategoryId(4); // 实习/兼职版块ID
        post.setTitle(internshipJobDTO.getJobTitle());
        post.setContent(internshipJobDTO.getJobDescription());
        post.setContactInfo(internshipJobDTO.getContactPhone());
        post.setLocation(internshipJobDTO.getWorkLocation());
        
        // 设置紧急状态和过期时间
        post.setIsUrgent(false);
        logger.info("设置isUrgent为: {}", post.getIsUrgent());
        
        if (internshipJobDTO.getDeadline() != null) {
            post.setExpiredAt(internshipJobDTO.getDeadline().atStartOfDay());
            logger.info("设置expiredAt为: {}", post.getExpiredAt());
        } else {
            logger.info("deadline为null，不设置expiredAt");
        }
        
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        
        logger.info("准备插入posts表: userId={}, categoryId={}, title={}, isUrgent={}, expiredAt={}", 
                   userId, 4, post.getTitle(), post.getIsUrgent(), post.getExpiredAt());
        logger.info("Post对象完整信息: {}", post);
        
        // 插入帖子信息
        try {
            postMapper.insert(post);
            logger.info("posts表插入成功");
        } catch (Exception e) {
            logger.error("插入posts表时发生异常: ", e);
            throw e;
        }
        
        // 获取刚插入的帖子ID
        Integer postId = post.getId();
        logger.info("posts表插入成功，postId={}", postId);
        
        // 3. 创建实习/兼职信息记录
        InternshipJobs internshipJobs = new InternshipJobs();
        BeanUtils.copyProperties(internshipJobDTO, internshipJobs);
        internshipJobs.setPostId(postId);
        internshipJobs.setCreatedAt(LocalDateTime.now());
        internshipJobs.setUpdatedAt(LocalDateTime.now());
        
        logger.info("准备插入internship_jobs表: postId={}, jobTitle={}", postId, internshipJobs.getJobTitle());
        
        // 插入实习/兼职信息
        try {
            jobMapper.insertInternshipJob(internshipJobs);
            logger.info("internship_jobs表插入成功");
        } catch (Exception e) {
            logger.error("插入internship_jobs表时发生异常: ", e);
            throw e;
        }
        
        // 4. 处理图片上传
        if (coverFile != null && !coverFile.isEmpty()) {
            logger.info("开始处理图片上传");
            
            // 生成唯一文件名并保存
            String originalFilename = coverFile.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            
            String normalizedUploadPath = uploadPath.replace("\\", "/");
            if (!normalizedUploadPath.endsWith("/")) {
                normalizedUploadPath += "/";
            }
            
            // 创建上传目录
            File uploadDir = new File(normalizedUploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            String filePath = normalizedUploadPath + fileName;
            coverFile.transferTo(new File(filePath));
            
            // 插入帖子图片信息
            PostImages postImage = new PostImages();
            postImage.setPostId(postId);
            postImage.setImageUrl("/uploads/" + fileName); // 保存图片的相对路径
            postImage.setSortOrder(0); // 设置排序字段
            postImage.setCreatedAt(LocalDateTime.now());
            postMapper.insertPostImages(postImage);
            
            logger.info("图片上传处理完成，图片路径: {}", postImage.getImageUrl());
        }
        
        logger.info("实习/兼职信息添加完成");
    }
    
    /**
     * 增加实习/兼职信息浏览次数（同时更新帖子浏览次数）
     * @param id 实习/兼职信息ID
     */
    @Transactional
    public void incrementViewCount(Integer id) {
        // 先获取对应的postId
        Integer postId = jobMapper.getPostIdById(id);
        
        // 更新实习/兼职信息浏览次数
        jobMapper.incrementViewCount(id);
        
        // 同时更新帖子浏览次数
        if (postId != null) {
            postMapper.incrementViewCount(postId);
        }
    }

    @Override
    public List<InternshipJobs> getIndustryList(String industry) {
        logger.info("获取行业领域列表");
        List<InternshipJobs> industryList = jobMapper.getIndustryList(industry);
        return industryList;
    }

    /**
     * 验证实习/兼职信息DTO的必要字段
     * @param dto 实习/兼职信息DTO
     * @throws IllegalArgumentException 当必要字段缺失或无效时抛出
     */
    private void validateInternshipJobDTO(InternshipJobDTO dto) throws IllegalArgumentException {
        if (dto == null) {
            throw new IllegalArgumentException("实习/兼职信息不能为空");
        }
        
        // 验证必要字段
        if (dto.getJobTitle() == null || dto.getJobTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("职位名称(jobTitle)不能为空");
        }
        
        if (dto.getJobType() == null || dto.getJobType().trim().isEmpty()) {
            throw new IllegalArgumentException("工作类型(jobType)不能为空");
        }
        
        if (!"internship".equals(dto.getJobType()) && 
            !"part_time".equals(dto.getJobType()) && 
            !"full_time".equals(dto.getJobType())) {
            throw new IllegalArgumentException("工作类型(jobType)必须是internship、part_time或full_time之一");
        }
        
        if (dto.getCompanyName() == null || dto.getCompanyName().trim().isEmpty()) {
            throw new IllegalArgumentException("公司名称(companyName)不能为空");
        }
        
        if (dto.getJobDescription() == null || dto.getJobDescription().trim().isEmpty()) {
            throw new IllegalArgumentException("职位描述(jobDescription)不能为空");
        }
        
        if (dto.getWorkLocation() == null || dto.getWorkLocation().trim().isEmpty()) {
            throw new IllegalArgumentException("工作地点(workLocation)不能为空");
        }
        
        if (dto.getContactPerson() == null || dto.getContactPerson().trim().isEmpty()) {
            throw new IllegalArgumentException("联系人(contactPerson)不能为空");
        }
        
        // 验证薪资范围
        if (dto.getMinSalary() != null && dto.getMaxSalary() != null) {
            if (dto.getMinSalary().compareTo(dto.getMaxSalary()) > 0) {
                throw new IllegalArgumentException("最低薪资(minSalary)不能大于最高薪资(maxSalary)");
            }
        }
        
        // 验证招聘人数
        if (dto.getRecruitmentCount() != null && dto.getRecruitmentCount() <= 0) {
            throw new IllegalArgumentException("招聘人数(recruitmentCount)必须大于0");
        }
        
        // 验证每周工作天数
        if (dto.getWeeklyDays() != null && (dto.getWeeklyDays() < 1 || dto.getWeeklyDays() > 7)) {
            throw new IllegalArgumentException("每周工作天数(weeklyDays)必须在1-7之间");
        }
    }
    
    /**
     * 获取所有实习/兼职信息列表
     * @return 实习/兼职信息列表
     */
    @Override
    public List<InternshipJobs> getAllInternshipJobs() {
        logger.info("获取所有实习/兼职信息列表");
        return jobMapper.getAllInternshipJobs();
    }
    
    /**
     * 根据ID获取实习/兼职信息详情
     * @param id 实习/兼职信息ID
     * @return 实习/兼职信息详情
     */
    @Override
    public InternshipJobs getInternshipJobById(Integer id) {
        logger.info("根据ID获取实习/兼职信息详情: id={}", id);
        return jobMapper.getInternshipJobById(id);
    }
    
    /**
     * 根据postId获取实习/兼职信息详情
     * @param postId 帖子ID
     * @return 实习/兼职信息详情
     */
    public InternshipJobs getInternshipJobByPostId(Integer postId) {
        logger.info("根据postId获取实习/兼职信息详情: postId={}", postId);
        return jobMapper.getInternshipJobByPostId(postId);
    }
}